package net.androy.smugmugtool;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.androy.smugmugtool.vo.SearchResult;

import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class SearchActivity extends Activity {
	/** Called when the activity is first created. */

	Vector<String> list = new Vector<String>();
	private Gallery g = null;
	SAXParser parser = null;
	private XMLReader reader = null;
	private XMLHandler handler = null;
	private ArrayAdapter<ImageView> adapter = null;
	private List images = new ArrayList();
	private List bitmaps = new ArrayList();
	private Handler mHandler = new Handler();
	private String keyword = "";
	private String mode = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			parser = factory.newSAXParser();
			setReader(parser.getXMLReader());

			setHandler(new XMLHandler(getImages()));

			getReader().setContentHandler(getHandler());

			// initList();
		} catch (Exception e) {
			Log.e("SmugMugMain", e.getMessage());
		}

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		Bundle extras = getIntent().getExtras();
		setKeyword((String) extras.get("keyword"));
		setMode((String) extras.get("mode"));

		setContentView(R.layout.gallery_1);
		setG((Gallery) findViewById(R.id.gallery));
		// Set the adapter to our custom adapter (below)
		getG().setAdapter(new ImageAdapter(this));

		getG().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v,
					final int position, long id) {
				final ImageView preview = (ImageView) findViewById(R.id.preview);
				//final TextView loadingTitle = (TextView) findViewById(R.id.loading_title);
				
				Bitmap image = BitmapFactory.decodeResource(SearchActivity.this.getResources(), android.R.drawable.progress_indeterminate_horizontal); 
				preview.setImageBitmap(image);
				preview.postInvalidate();
				
//				loadingTitle.setTextColor(Color.WHITE);
//				loadingTitle.setText("Loading...");
//				loadingTitle.postInvalidate();

				Runnable rr = new Runnable() {
					public void run() {
						

						String url = ((SearchResult) images.get(position))
								.getGuid();

						url = url.substring(0, url.lastIndexOf("-Ti")).concat(
								"-S").concat(".jpg");

						try {
							URL aURL = new URL(url);
							URLConnection conn = aURL.openConnection();
							conn.connect();
							InputStream is2 = conn.getInputStream();
							/*
							 * Buffered is always good for a performance plus.
							 */
							BufferedInputStream bis = new BufferedInputStream(
									is2, 16384);
							/* Decode url-data to a bitmap. */
							final Bitmap bm = BitmapFactory.decodeStream(bis);
							bis.close();
							is2.close();

							mHandler.post(new Runnable() {
								public void run() {
									preview.setImageBitmap(bm);
									preview.postInvalidate();
									//loadingTitle.setText("");
									//loadingTitle.postInvalidate();

								}
							});

						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				};

				new Thread(rr).start();

				// TextView title = (TextView) findViewById(R.id.preview_title);
				// title.setText(((SearchResult)
				// images.get(position)).getTitle());

				// title.postInvalidate();
			}
		});

		// We also want to show context menu for longpressed items in the
		// gallery
		registerForContextMenu(getG());

	}

	@Override
	protected void onStart() {
		super.onStart();

		// setProgressBarIndeterminate(true);
		Runnable r = new Runnable() {
			public void run() {
				setProgressBarIndeterminateVisibility(true);
			}
		};

		runOnUiThread(r);

		Thread t = new Thread(new SmugMugRetriever(this));
		t.start();

	}

	public void setReader(XMLReader reader) {
		this.reader = reader;
	}

	public XMLReader getReader() {
		return reader;
	}

	public void setHandler(XMLHandler handler) {
		this.handler = handler;
	}

	public XMLHandler getHandler() {
		return handler;
	}

	public void setAdapter(ArrayAdapter<ImageView> adapter) {
		this.adapter = adapter;
	}

	public ArrayAdapter<ImageView> getAdapter() {
		return adapter;
	}

	public void setImages(List images) {
		this.images = images;
	}

	public List getImages() {
		return images;
	}

	public void setBitmaps(List bitmaps) {
		this.bitmaps = bitmaps;
	}

	public List getBitmaps() {
		return bitmaps;
	}

	public void setG(Gallery g) {
		this.g = g;
	}

	public Gallery getG() {
		return g;
	}

	public void setMHandler(Handler mHandler) {
		this.mHandler = mHandler;
	}

	public Handler getMHandler() {
		return mHandler;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;

		public ImageAdapter(Activity c) {
			activity = c;

			TypedArray a = obtainStyledAttributes(android.R.styleable.Theme);
			mGalleryItemBackground = a.getResourceId(
					android.R.styleable.Theme_galleryItemBackground, 0);
			a.recycle();
		}

		public int getCount() {
			return bitmaps.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView iv = new ImageView(SearchActivity.this);
			iv.setVerticalFadingEdgeEnabled(true);
			iv.setFadingEdgeLength(1000);

			// TextView title =
			// (TextView)activity.findViewById(R.id.preview_title);
			// title.setText(((SearchResult)images.get(position)).getTitle());

			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			iv.setLayoutParams(new Gallery.LayoutParams(136, 88));

			// The preferred Gallery item background
			iv.setBackgroundResource(mGalleryItemBackground);

			iv.setImageBitmap((Bitmap) bitmaps.get(position));

			return iv;
		}

		private Activity activity;
	}

}

class SmugMugEntry {
	private String id;
	private String title;

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return super.toString();
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}
}